home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11079 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Virtual Base Class
  5. Date: Tue, 12 Mar 1996 16:40:14 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4i49c5$qtc@news.halcyon.com>
  8. References: <313F98D0.102E@ucla.edu> <4i1gnv$b7i@uuneo.neosoft.com>
  9. NNTP-Posting-Host: blv-pm3-ip12.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Wmatthew@lan-aces.com (W. Matthews) wrote:
  13.  
  14. >In article <313F98D0.102E@ucla.edu>, Dennis Rahaman <dennisr@ucla.edu> says:
  15. >>
  16. >>This is what I want to do:
  17. >>
  18. >>              a
  19. >>            /   \
  20. >>           b     c
  21. >>            \   /
  22. >>              d
  23. >>
  24. >>
  25. >>class b : public virtual a
  26. >>  {
  27. >>  //...
  28. >>  };
  29. >>
  30. >>class c : public virtual b
  31. >>  {
  32. >>  //...
  33. >>  };
  34. >>
  35. >>class d : public b, public c
  36. >>  {
  37. >>  //...
  38. >>  };
  39. >>
  40. >>
  41. >>void f ()
  42. >>  {
  43. >>  a a1;
  44. >>  d* pd = (d*) &a1;  // error: can't cast virtual base to derived
  45. >>  }
  46. >>
  47. >>///////////////////////////////////////////////////////////
  48. >>Can someone explain why I can't cast a virtual base class to a derived 
  49. >>class?
  50. >>
  51. >>What should I do instead?
  52. >>
  53.  
  54. If your compiler supports Run-Time Type Information (RTTI), enable it
  55. and use dynamic_cast<d *>(pa).  If the cast cannot succeed (if d
  56. weren't really derived from a), it will return NULL, otherwise the
  57. cast succeeds.  Down-casting to derived classes is otherwise extremely
  58. risky; you could be lying and telling the compiler to look the other
  59. way.  Using dynamic_cast<> is best.
  60.  
  61.                         --Norm 
  62.  
  63.  
  64.  
  65.